// ==UserScript==
// @name           Wootoff
// @namespace      http://meat.net/
// @description    Checks the progress bar during a wootoff without doing a full refresh
// @include        http://www.woot.com/
// @include        http://woot.com/
// ==/UserScript==

String.prototype.rtrim=function(){ return this.replace(/\s+$/g,''); }

    if (console == undefined) {
	function GM_log(foo) { 
	    // do nothing
	}
    } else {
	function GM_log(foo) {
	    console.log(foo);
	}
    }

var updater = {
    id: function(id)
    {
	return document.getElementById(id);
    },
    init: function()
    {
	var $ = unsafeWindow.$;
	GM_log("init()");
	var wootContainer = $(".wootOff");
	if (wootContainer.length == 0) {
	    GM_log("not a wootoff");
	    return;
	}
	bars = $(".wootOffProgressBarValue");
	if (bars.length > 0) 
	    this.bar = bars[0];
	this.title = $('.productDescription h2')[0].textContent;
	GM_log(this.title);
	this.wakeup();
    },
    wakeup: function()
    {
	GM_log("requesting microsummary");
	GM_xmlhttpRequest({
	    method: 'GET',
		    url: 'http://www.woot.com/DefaultMicrosummary.ashx',
		    onload: function(deets) { updater.onload(deets); },
		    onerror: function(deets) { updater.sleep(); },
		    });
    },
    onload: function(deets)
    {
	GM_log("got microsummary: " + deets.status + ", " + deets.responseText);
	if (deets.status == 200)
	{
	    text = deets.responseText.split('\n')[0];
	    document.title = text + " : Woot : WOOTOFF!";
	    flds = text.split(' : ');
	    newitem = flds[2].rtrim();
	    if (newitem.replace(/\s/g,'') == this.title.replace(/\s/g,''))
	    {
		this.bar.style.width = flds[0];
		this.sleep();
	    }
	    else
	    {
		document.title += " ... reloading";
		window.location.reload(true);
	    }
	}
    },
    sleep: function()
    {
        GM_log("going to sleep");
	window.setTimeout(function() { updater.wakeup() }, 30000);
    },
    toString: function() {
	return "[wootoff updater object]";
    }
};

GM_log(updater);
updater.init();
